package com.example.designPattern.Proxy.JDKDynamicProxy;



import org.springframework.util.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;


public class MyClassLoader extends ClassLoader {

    private File filePath;

    public MyClassLoader() {
        String path= MyClassLoader.class.getResource("").getPath();
        this.filePath = new File(path);
    }

    @Override
    protected Class<?> findClass(String clsName) throws ClassNotFoundException {
        try{
        String className = MyClassLoader.class.getPackage().getName() + "." + clsName;
        if(StringUtils.isEmpty(className))return  null;

        File classFile = new File(this.filePath,clsName.replaceAll("\\.","/") + ".class");
        if(!classFile.exists()) return null;

            FileInputStream in = null;
            ByteArrayOutputStream out = null;

            in = new FileInputStream(classFile);
            out = new ByteArrayOutputStream();
            byte [] buff = new byte[1024];
            int len;
            while ((len = in.read(buff)) != -1){
                out.write(buff,0,len);
            }
            return defineClass(className,out.toByteArray(),0,out.size());

        }catch (Exception ex){
            ex.printStackTrace();
        }
        return  null;
    }

}
